package com.fanshuai.jmx.jvm;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.Arrays;

public class ThreadReporter {
    public static void reportThreads() {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

        //thread count
        int threadCount = threadMXBean.getThreadCount();
        int deamonThreadCount = threadMXBean.getDaemonThreadCount();
        System.out.println("thread count=" + threadCount + ", " + deamonThreadCount);

        //cpu time
        long cpuTime = threadMXBean.getCurrentThreadCpuTime();
        long userTime = threadMXBean.getCurrentThreadUserTime();

        System.out.println("cpu time=" + cpuTime + "," + userTime);

        //thread id
        long[] ids = threadMXBean.getAllThreadIds();
        Arrays.stream(ids).forEach(System.out::println);

        //thread dump
        ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
        Arrays.stream(threadInfos).forEach(threadInfo -> {
            Arrays.stream(threadInfo.getStackTrace()).forEach(System.out::println);

            System.out.println("\n\n\n");
        });

    }
}
